import {
	config,
	TOKEN_PRE
} from '../request/config.js'

class HTTP {
	constructor() {
		this.baseUrl = config.base_url
	}

	request({
		url,
		data = {},
		method = 'get',
		isToken=false
	}) {
		return new Promise((resolve, reject) => {
			this._request(url, resolve, reject, data, method,isToken)
		})
	}

	_request(url, resolve, reject, data = {}, method = 'get',isToken) {
		const requestConfig = {
			url: `${this.baseUrl}${url}`,
			method: method,
			data: data,
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				// 'appId': config.appId,
				'token': TOKEN_PRE+uni.getStorageSync('token')
			},
			success: (res) => {
				if (res.data.code===200) {
					const _success = res.data.success;
					if (_success) {
						resolve(res.data)
					} else {
						resolve(res.data)
						const error_code = res.data.code;
						const _message = res.data.data;
						this._show_error(error_code, _message)
					}
				} else {
					switch(res.data.code){
						case 401:
							console.log('登录过期')
							uni.removeStorageSync('token')
							uni.navigateTo({
								url:'/pages/UserCenter/Login/Login'
							})
							break
					}
				}
			},
		}
		!isToken && (delete requestConfig.header.token)
		uni.request(requestConfig)
	}

	_show_error(error_code, _message) {
		uni.showToast({
			title: `${_message}`,
			icon: 'error',
			duration: 2000
		})
	}
}

export {
    HTTP
}